<template>
  <div>
    <div>
      <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        sub-title="查看用户"
        @back="fanhui()"
      />
    </div>
    <div class="content">
      <div>
        <a-button type="dashed" @click="TianUser">角色权限分配</a-button>
        <ZhuCheUser style="display: -webkit-inline-box;"></ZhuCheUser>
        <!-- 编辑 -->
        <div style="float: right">
          <a-button type="primary" :disabled="!hasSelected" :loading="loading" @click="newcongstart">重置密码</a-button>
          <span style="margin-left: 8px">
            <template v-if="hasSelected">{{ `Selected ${selectedRowKeys.length} items` }}</template>
          </span>
        </div>
        <!-- 删除 -->
        <div style="float: right;margin-right: 3%;">
          <a-button
            type="primary"
            :disabled="!delstarthasSelected"
            :loading="loading"
            @click="delstart()"
          >删除数据</a-button>
        </div>
        <!-- <div>
          <el-input
            style="
              width: 200px;
              margin-right: 20px;
              margin-top: 20px;
              z-index:500
            "
            placeholder="根据关键字查询题目列表"
            v-model="input"
            clearable
          >
          </el-input>
          <el-button style="z-index:1600" type="primary" icon="el-icon-search" @click="but">搜索</el-button>        
        </div> -->
      </div>
      <div style="margin-top:10px">
        <div>
          <!-- 列表 -->
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :data-source="data"
            :rowClassName="rowClassName"
            :pagination="false"
          >
            <span slot="status" slot-scope="status, record">
              <a-switch
                size="small"  
                :checked="Boolean(record.status)"  
                @change="onChange($event, record)"   
              />
            </span>
          </a-table>
        <div class="block">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="list.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="list.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="list.total"
          ></el-pagination>
        </div>
        </div>
      </div>
    </div>
    <!-- 编辑 -->
    <el-drawer
      title="用户修改,全选只能修改角色权限"
      :before-close="handleClose"
      :visible.sync="dialog"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content" style="font-size: 20px;margin-left: 2%;font-weight: bold;">
        <el-form :model="form">
          <el-form-item label="用户名:">
            <el-input disabled v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码:">
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="别名:">
            <el-input disabled v-model="form.alias" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="状态:">
            <el-input disabled v-model="form.type" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="权限:">
            <el-select disabled v-model="form.userId" clearable placeholder="请选择">
              <el-option
                v-for="item in userId"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="float: right;margin-right: 5%;">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            type="primary"
            @click="$refs.drawer.closeDrawer()"
            :loadings="loadings"
          >{{ loadings ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import UserorRoleget from "../api/UserorRole";
// import UserorRole from "../Mockjs/UserorRole/UserorRole";
import ZhuCheUser from "./zhuCheUser.vue";
const columns = [

  {
    title: "用户名",
    dataIndex: "username"
  },
  {
    title: "角色",
    dataIndex: "roleName"
  },
  {
    title: "时间",
    dataIndex: "updateTime"
  },
  {
    title:"状态",
    scopedSlots: { customRender: 'status' },
  }
];

const data = [];

export default {
  data() {
    return {
      userId: [],
      data,
      columns,
      selectedRowKeys: [],
      loading: false,
      dialog: false,
      loadings: false,
      form: {},
      // 分页
      list:{
        total:0, // 总页数
        pageTotal:0, 
        page:0,
        pageSize:0,
      },
      input:''
    };
  },
  components: {
    ZhuCheUser
  },
  created() {
    this.dataget();
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
    delstarthasSelected() {
      return this.selectedRowKeys.length > 0;
    },
    handleIndex() {
      return this.list.pageSize * (this.list.page - 1) + 1
    }
  },
  methods: {
    // 表格背景色
    rowClassName(record){
      if(record.status === 0){
        // console.log(index)
        let a123 = "table-back"
        return a123
      }
    },
    // 分页
    // 当前第几页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.list.pageSize = val
      UserorRoleget.yemian(val).then(res=>{
        data.splice(0, data.length);
        for (var i = 0; i < res.data.list.list.length; i++) {
          data.push(res.data.list.list[i]);
        }
      })
    },
    // 每页多少条
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.list.page = val
      UserorRoleget.danqina(val,this.list.pageSize).then(res=>{
        data.splice(0, data.length);
        for (var i = 0; i < res.data.list.list.length; i++) {
          data.push(res.data.list.list[i]);
        }
      })
    },
    // 删除
    delstart() {
      var con = confirm(
        `你确定要删除这 ${this.selectedRowKeys.length} 条数据吗？`
      );
      if (con == true) {
        if(this.selectedRowKeys.length > 1){
          var userIds = []
          console.log(this.selectedRowKeys)
          for(var j=0;j<this.selectedRowKeys.length;j++){
            console.log(this.selectedRowKeys[j])
            userIds.push(data[this.selectedRowKeys[j]].userId)
            console.log(data[this.selectedRowKeys[j]].userId)
          }
          console.log(userIds)
          UserorRoleget.Roledele(userIds).then(res => {
            if(res.data.code === 20000){
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'success'
              });
              // location.reload();
              this.dataget();
              this.selectedRowKeys = []
            }else{
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
            }
          });
        }else{
          console.log(data[this.selectedRowKeys].userId)
          UserorRoleget.Roledele(data[this.selectedRowKeys].userId).then(res => {
            if(res.data.code === 20000){
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'success'
              });
              this.dataget();
              this.selectedRowKeys = []
            }else{
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
            }
          });
        }
       }
    },
    // 修改
    start() {
      this.loading = true;
      if (this.selectedRowKeys.length > 1) {
        alert("修改只能选着一个值");
        this.loading = false;
      } else {
        this.form = data[this.selectedRowKeys];
        // console.log(this.form)
        this.dialog = true;
        UserorRoleget.Rolegetjiao().then(res => {
          this.userId = res.data.list.list
          // console.log(this.userId)
        });
      }
    },
    // 修改二次修改 第一个修改废弃，改成重置密码
    newcongstart(){
    if (this.selectedRowKeys.length > 1) {
        alert("修改只能选着一个值");
    } else {
      this.form = data[this.selectedRowKeys];
      UserorRoleget.Roleputs(this.form).then(res => {
          console.log(res);
          if(res.data.code === 500) {
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
          } 
          if(res.data.code === 20000){
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'success'
              });
            this.dataget();
            this.selectedRowKeys = []
          }
      });
    }
    },
    // 查询根据用户查看脚色
    pushuserId(){
      // UserorRole.JuserId()
      var id = data[this.selectedRowKeys].userId
      UserorRoleget.Roleuserandget(id).then(res=>{
        for(var i=0;i<res.data.length;i++){
          this.userId.push(res.data[i])
          if(res.data[i].checked == true){
            return this.roleId = res.data[i].RoleName  
          }
        }
      })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 用户数据
    dataget() {
      data.splice(0, data.length);
      UserorRoleget.Roleget().then(res => {
        // console.log(res.data)
        if(res.data.code === 401){
          localStorage.clear();
        }
        if(res.data.code === 500){
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
        }
        for (var i = 0; i < res.data.list.list.length; i++) {
          data.push(res.data.list.list[i]);
        }
        // 分页赋值
        this.list = {
          total:Number(res.data.list.total), // 总页数
          pageTotal:res.data.list.pageTotal, 
          page:res.data.list.page, // 当前页
          pageSize: res.data.list.pageSize,
        }
        // console.log(this.list)
      });
    },
    // 确定修改 用户数据 
    handleClose(done) {
      if (this.loadings) {
        return;
      }
      this.$confirm("确定要提交表单吗？")
        .then(() => {
          // console.log(this.form)
          UserorRoleget.Roleput(this.form).then(res => {
            // console.log(res);
            if(res.data.code === 500) {
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
            } 
          });
          this.loadings = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loadings = false;
              this.loading = false;
              this.selectedRowKeys = [];
            }, 400);
          }, 1000);
        })
        .catch(() => {});
    },
    cancelForm() {
      this.loadings = false;
      this.dialog = false;
      this.loading = false;
      this.selectedRowKeys = [];
      clearTimeout(this.timer);
    },
    TianUser() {
      this.$router.push("/Userpush?name=用户管理");
    },
    fanhui() {
      this.$router.push("/management?name=用户资料");
    },
	//调整用户状态
    onChange(e, record) {
      //确认框中用到的当前作用域this需要提前替换为局部变量，否则浏览器会提示无法获取该属性。
      // let self = this
      // this.$confirm({
        // title: "确认修改此用户的状态信息？",
        //自定义按钮内容
        // okText: "确认",
        // cancelText: "取消",
        // onOk() {
          // let values;
          // console.log(123123)
          //根据开关状态初始化，传入后台的值
          // if(e){
            // values = {id:record.id,status:1}
            // record.status=1
          // }else{
            // values = {id:record.id,status:0}
            // record.status=0
          // }
          //调用后台方法修改用户状态
          // UserorRoleget.axiosPostApi(values).then((resp) => {
            // if (resp.code == 20000) {
              //根据修改后的信息，调整前端数据集中的数据内容，这样就不用重新请求后台数据了。实现无刷新更新数据
              // self.$set(self.userData, self.userData.indexOf(record), record)    
            // }
          // });
        // },
        // onCancel() {},
      // });
      // 状态状态状态状态状态状态状态状态状态状态状态状态状态
      this.$confirm('确定停用该条消息吗 ?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
      .then(() => {
        let values;
        console.log(record)
        if(e){
          values = {userId:record.userId,status:1}
          record.status=1
        }else{
          values = {userId:record.userId,status:0}
          record.status=0
        }
        UserorRoleget.axiosPostApi(values).then((res) => {
          if(res.data.code === 500) {
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
            this.dataget();
          }else if(res.data.code === 20000) {
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'success'
              });
            this.dataget();
          }else if(res.data.code === 401){
            localStorage.clear();
          }else if(res.data.msg === "账号已被锁定,请联系管理员"){
              this.$message({
                showClose: true,
                message:res.data.msg,
                type: 'error'
              });
            localStorage.clear();
          }
        });
      })
      .catch(() => {})
    },
  }
};
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.content {
  width: 80%;
  margin: auto;
  margin-top: 20px;
}
.block {
  margin-top: 20px;
  float: right;
}
div /deep/.table-back {
   background-color: #dadada57;
}
</style>